<template>
  <div class="pagination" style="text-align: center">
    <button @click="currentPage -= 1" :disabled="currentPage === 1">
      上一页
    </button>
    <button v-show="startEnd.startPage > 1" @click="currentPage = 1">1</button>
    <button v-show="startEnd.startPage > 2">···</button>

    <button
      v-for="(page, index) in totalPage"
      :key="index"
      @click="currentPage = page"
      :class="{ active: page === currentPage }"
      v-if="page >= startEnd.startPage && page <= startEnd.endPage"
    >
      {{ page }}
    </button>

    <button v-show="startEnd.endPage < totalPage - 1">···</button>
    <button
      v-show="startEnd.endPage < totalPage"
      @click="currentPage = totalPage"
    >
      {{ totalPage }}
    </button>
    <button @click="currentPage += 1" :disabled="currentPage === totalPage">
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ totalSize }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["totalSize", "pageSize", "initPage", "connectPageNum"],
  data() {
    return {
      currentPage: this.initPage,
    };
  },
  computed: {
    totalPage() {
      let totalSize = this.totalSize * 1;
      let pageSize = this.pageSize * 1;
      return Math.ceil(totalSize / pageSize);
    },
    //定义连续开始页和结束页
    startEnd() {
      let startPage = 0;
      let endPage = 0;
      let connectPageNum = this.connectPageNum * 1; //先转为number类型
      let currentPage = this.currentPage * 1;
      let totalPage = this.totalPage; //用来判断特殊情况
      //正常情况下
      startPage = currentPage - Math.floor(connectPageNum / 2);
      //初始页异常
      if (startPage < 1) {
        startPage = 1;
      }
      endPage = startPage + connectPageNum - 1;
      //结束页异常
      if (endPage > totalPage) {
        endPage = totalPage;
        startPage = endPage - connectPageNum + 1;
        //都异常
        if (startPage < 1) {
          startPage = 1;
        }
      }
      return {
        startPage,
        endPage,
      };
    },
  },
  watch: {
    currentPage(page) {
      this.$emit("pageChange", page);
    },
    initPage(page) {
      this.currentPage = page;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>